<?php

namespace App\V3\V3_2_6\Services;

use App\V3\V3_2_6\Models\StorageModel;
use App\V3\V3_2_6\Models\StorageManageModel;
use Illuminate\Support\Facades\DB;
use App\V3\V3_2_6\Models\StorageBatchModel;
use App\V3\V3_2_6\Models\SellPackageDetailModel;
use App\V3\V3_2_6\Models\SellPackageContentModel;
use App\V3\V3_2_6\Models\CheckStorageManageModel;
use App\V3\V3_2_6\Models\SerialNumberModel;
use App\V3\V3_2_6\Models\MaterielTypeModel;
use App\V3\V3_2_6\Models\CheckSerialNumberModel;
use App\V3\V3_2_6\Models\MaterielProductContentModel;
class CheckStorageManageService
{

    //仓库列表
    static public function getStorageList($mainId,$data)
    {
        return StorageModel::select('id','storage_name')
            ->where('main_id', $mainId)
            ->where('delete_flag', 0)
            ->orderBy('id', 'DESC')->get()->toArray();
           /*  ->paginate($data['pageSize'],['*'], '',$data['currentPage']); */
    }

    static public function getStorageGoodsList($storageId,$data,$keyword,$typeId){

         $query = StorageManageModel::select(
            'a.id',
            'type_id',
            'b.materiel_name',
            'b.materiel_img',
            'c.shelf_name',
            'd.location_name',
            'a.type_name',
            'a.materiel_no',
             'b.is_product_materiel',
             'b.is_use_serial',
             'b.selling_price',
             'b.materiel_unit',
            DB::raw('SUM(in_storage_num) as total_amount')
            )
            ->from('storage_manage as a')
            ->leftJoin('materiel_type as b', 'b.id', '=', 'a.type_id')
            ->leftJoin('storage_shelf as c', 'c.id', '=', 'a.shelf_id')
            ->leftJoin('storage_shelf_location as d', 'd.id', '=', 'a.location_id')
            ->leftJoin('materiel_class as e', 'e.id', '=', 'b.materiel_class_id')
            ->leftJoin('materiel_class as f', 'e.parent_id', '=', 'f.id')
            ->with('productContent',function($query){
                $query->select(
                    'materiel_product_content.id',
                    'a.materiel_name',
                    'a.type_name',
                    'a.materiel_img',
                    'a.materiel_no',
                    'materiel_product_content.type_id',
                    'product_id',
                    'materiel_product_content.num',
                    'materiel_product_content.price',
                    'materiel_product_content.total_price'
                    )->leftJoin('materiel_type as a', 'a.id', '=', 'materiel_product_content.type_id')
                    ->where('materiel_product_content.delete_flag',0)
                    ->where('a.delete_flag',0);
            })
            ->where('a.main_id', $data['main_id'])
            ->where('a.storage_id',$storageId);
            if(!empty($data['materiel_class_id'])) {
                $query->where('b.materiel_class_id',$data['materiel_class_id']);
            }

            if(!empty($typeId)) {

                $query->whereIn('a.type_id', $typeId);
            }
            return $query->where(function($query) use ($keyword) {
                $query->orWhere('a.materiel_name', 'like', '%'.$keyword.'%');
                $query->orWhere('a.type_name', 'like', '%'.$keyword.'%');
                $query->orWhere('a.materiel_no', 'like', '%'.$keyword.'%');
                $query->orWhere('e.class_name', 'like', '%'.$keyword.'%');
                $query->orWhere('f.class_name', 'like', '%'.$keyword.'%');
            })
            ->where('a.delete_flag',0)
            ->where('b.delete_flag',0)
            ->groupBy('type_id')
            ->groupBy('location_id')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);
    }
 //识别条码
    static public function readBatchNo($data)
    {
        $subBatchInfo = substr($data['batch_no'], -1, 1);
        if($subBatchInfo == 'a') {
            $result = self::readSellPackage($data['batch_no']);
            if(empty($result)) {
                return ['code' => 1, 'msg' => '暂无条码信息', 'data' => ''];
            }
        }
        else {

            $condition=[];
            if($data['code_type']==0){
                $condition['id'] = substr($data['batch_no'],5,strlen($data['batch_no'])-1);
            }elseif($data['code_type']==1){
                $condition['id'] = $data['goods_id'];
                $sInfo = SerialNumberModel::where([
                    'serial_no'=>$data['batch_no'],
                    'goods_id'=>$data['goods_id']
                    ])->first();
            }elseif($data['code_type'] == 3){
                $mInfo = MaterielTypeModel::where([
                    'main_id'     => $data['main_id'],
                    'delete_flag' => 0,
                    'bar_code'    =>$data['batch_no']
                ])->first();

                if(empty($mInfo)){
                    $mList = MaterielTypeModel::where([
                        'main_id'   => $data['main_id'],
                        'delete_flag' => 0
                    ])->where('number_prefix','!=','')->get()->toArray();

                    if(!empty($mList)){
                        foreach ($mList as $val){
                            if(strpos($data['batch_no'], $val['number_prefix']) !== false){
                                $condition['id'] = $val['id'];
                            }
                        }
                    }
                }
                if(empty($condition['id'])){
                    $condition['bar_code'] = $data['batch_no'];
                }
            }
//            if(!empty($condition)){
//                $info = MaterielTypeModel::where($condition)
//                    ->where(['main_id' => $data['main_id'], 'delete_flag' => 0])->first();
//                if (!empty($info)) {
//                    if ($info['is_product_materiel'] == 1) {//是套餐
//                        $data['goods_id'] = $info['id'];
//                        $data['is_product'] = 1;
//                    }
//                    if(empty($info['is_product_materiel']) && $data['code_type'] != 3) {//套餐里的商品
//                        if(!empty($sInfo['parent_id'])||($data['code_type'] != 1)){
//                            $pInfo = MaterielProductContentModel::where([
//                                'type_id' => $info['id'],
//                                'main_id' => $data['main_id'],
//                                'delete_flag' => 0
//                            ])->first();
//
//                            if (!empty($pInfo['product_id'])) {
//                                $data['goods_id'] = $pInfo['product_id'];
//                                $data['is_product']=1;
//                            }
//                        }
//                    }
//
//                } else {
//                    $result = ['code' => 1, 'msg' => '商品信息，不存在!', 'data' => ''];
//                }
//                unset($condition);
//            }

            if($data['code_type']==0 && strpos($data['batch_no'], 'smycg')!==false){//物料商品id
                $data['batch_no'] = substr($data['batch_no'],5,strlen($data['batch_no'])-1);

                $result = self::readGoodsInfo($data);
                if(empty($result)) {
                    return ['code' => 1, 'msg' => '该商品，不属于此账号！', 'data' => ''];
                }
            }elseif($data['code_type']==2 && strpos($data['batch_no'], $data['batch_title'])!==false){
                $result = self::readMateriel($data['batch_no']);
                if(empty($result)) {
                    return ['code' => 1, 'msg' => '该商品，不属于此账号！', 'data' => ''];
                }
            }elseif($data['code_type']==1){//序列号
                $result ="";
                if(!empty($data['goods_id']) && !empty($data['batch_no'])){

                $result = self::readSerialNumber($data);
                    if(empty($result)) {
                        return ['code' => 1, 'msg' => '该商品，不属于此账号！', 'data' => ''];
                    }
                }
            }elseif ($data['code_type'] == 3){//条形码
                $result ="";
                if(!empty($data['batch_no'])){

                    $result = self::readBarCodeGoodsInfo($data);
                    if(empty($result)) {
                        return ['code' => 1, 'msg' => '该商品，不属于此账号！', 'data' => ''];
                    }
                }
            }
        }

        return ['code' => 0, 'msg' => 'success', 'data' => $result];
    }
    /**
     * 序列号查询（打码）
     * @param unknown $serialNubmer
     */
    static private function readSerialNumber($data){

        //查询是否是组件序列号，如果是返回组件套餐id
             $query = SerialNumberModel::select(
                'b.id',
                'b.type_id',
                'c.materiel_name',
                'c.materiel_img',
                'd.shelf_name',
                'e.location_name',
                'c.type_name',
                'c.materiel_no',
                'b.storage_name',
                'b.storage_id',
                'b.shelf_id',
                'b.location_id',
                'c.selling_price',
                'c.is_use_serial',
                'c.is_product_materiel',
                'c.length',
                'c.width',
                'c.height',
                'c.weight',
                'c.attribute',
                'c.cost',
                'c.last_cost',
                'c.lower_selling_price',
                'c.remark',
                 'a.package_storage_id',
                 'a.package_id',
                DB::raw('SUM(in_storage_num) as total_amount')
                )->from('serial_number as a');
            $serialInfo = SerialNumberModel::where(['serial_no'=>$data['batch_no'],'goods_id'=>$data['goods_id']])->first();
            if(!empty($serialInfo['parent_id'])){
                $serialInfo = SerialNumberModel::where(['id'=>$serialInfo['parent_id']])->first();
            }
           if(empty($serialInfo)) return "";
            $query -> leftJoin('storage_manage as b', 'b.id', '=', 'a.storage_manage_id')
                -> leftJoin('materiel_type as c', 'b.type_id', '=', 'c.id')
                -> leftJoin('storage_shelf as d', 'd.id', '=', 'b.shelf_id')
                -> leftJoin('storage_shelf_location as e', 'e.id', '=', 'b.location_id')
                -> where('a.serial_no', $serialInfo['serial_no'])
                -> where('a.goods_id', $serialInfo['goods_id']);

                $info = $query->where('b.main_id',$data['main_id'])
                        ->where('b.delete_flag',0)
                        ->where('c.delete_flag',0)
                        ->first();

               $info['product_content'] =[];
               if(!empty($info) && $info['is_product_materiel'] == 1){
                  $productList = MaterielProductContentModel::select(
                              'a.id',
                              'b.materiel_name',
                              'b.type_name',
                              'b.materiel_img',
                              'b.materiel_no',
                              'a.product_id',
                              'a.num',
                              'a.price',
                              'a.type_id',
                              'a.total_price'
                              )
                          ->from('materiel_product_content as a')
                          ->leftJoin('materiel_type as b','b.id','=','a.type_id')
                          ->where('a.product_id',$info['type_id'])->get()->toArray();
                          if(!empty($productList)){
                              $info['product_content'] = $productList;
                          }
                   }
                    if(!empty($info['id'])){
                            return $info;
                    }else{
                        return "";
                    }
    }

    static private function readSellPackage($batchNo)
    {
        $packageInfo = SellPackageDetailModel::select('a.id')
            ->from('sell_package_detail as a')
            ->leftJoin('package as b', 'b.id', '=', 'a.package_id')
            ->where('package_no', $batchNo)
            ->first()->toArray();

         return  SellPackageContentModel::select(
                'b.id',
                'b.type_id',
                'a.materiel_name',
                'a.materiel_img',
                'd.shelf_name',
                'e.location_name',
                'a.selling_price',
                'a.is_use_serial',
                'b.storage_name',
                'b.storage_id',
                'b.shelf_id',
                'b.location_id',
                 DB::raw('SUM(in_storage_num) as total_amount')
                )->from('sell_package_content')
                ->leftJoin('materiel_type as a', 'a.id', '=', 'sell_package_content.materiel_type_id')
                ->leftJoin('storage_manage as b', 'b.id', '=', 'sell_package_content.storage_manage_id')
                ->leftJoin('storage_shelf as d', 'd.id', '=', 'b.shelf_id')
                ->leftJoin('storage_shelf_location as e', 'e.id', '=', 'b.location_id')
                ->where('package_detail_id',$packageInfo['id'])
                ->where('a.delete_flag',0)
                ->where('b.delete_flag',0)
                ->first();
    }

    //商品批次信息
    static private function readMateriel($batchNo)
    {
         $info = StorageBatchModel::select(
            'b.id',
            'b.type_id',
            'c.materiel_name',
            'c.materiel_img',
            'd.shelf_name',
            'e.location_name',
            'c.type_name',
            'c.materiel_no',
            'b.storage_name',
            'b.storage_id',
            'b.shelf_id',
            'b.location_id',
            'c.selling_price',
            'c.is_use_serial',
            'c.is_product_materiel',
            'c.length',
            'c.width',
            'c.height',
            'c.weight',
            'c.attribute',
            'c.cost',
            'c.last_cost',
            'c.lower_selling_price',
            'c.remark',
             DB::raw('SUM(in_storage_num) as total_amount')
            )
            ->from('storage_batch as a')
            ->leftJoin('storage_manage as b', 'b.id', '=', 'a.storage_manage_id')
            ->leftJoin('materiel_type as c', 'b.type_id', '=', 'c.id')
            ->leftJoin('storage_shelf as d', 'd.id', '=', 'b.shelf_id')
            ->leftJoin('storage_shelf_location as e', 'e.id', '=', 'b.location_id')
            ->where('batch_no', $batchNo)
            ->where('b.delete_flag',0)
            ->where('c.delete_flag',0)
            ->where('a.delete_flag',0)
            ->first();
            $info['product_content'] = [];
            if(!empty($info) && $info['is_product_materiel'] == 1){
                 $productList = MaterielProductContentModel::select(
                     'a.id',
                     'b.materiel_name',
                     'b.type_name',
                     'b.materiel_img',
                     'b.materiel_no',
                     'a.product_id',
                     'a.num',
                     'a.price',
                     'a.type_id',
                     'a.total_price'
                     )
                     ->from('materiel_product_content as a')
                     ->leftJoin('materiel_type as b','b.id','=','a.type_id')
                     ->where('a.product_id',$info['type_id'])->get()->toArray();
                     if(!empty($productList)){
                         $info['product_content'] = $productList;
                     }
             }
            return $info;
    }

    //商品批次信息
    static private function readGoodsInfo($data)
    {
        //查询是否是组件id，如果是返回组件套餐id
        $query = MaterielTypeModel::select(
            'b.id',
            'a.id as type_id',
            'd.shelf_name',
            'e.location_name',
            'b.storage_name',
            'b.storage_id',
            'b.shelf_id',
            'b.location_id',
            'a.materiel_name',
            'a.materiel_img',
            'a.type_name',
            'a.materiel_no',
            'a.selling_price',
            'a.is_use_serial',
            'a.materiel_class_id',
            'a.materiel_unit',
            'a.is_album',
            'a.is_product_materiel',
            'a.length',
            'a.width',
            'a.height',
            'a.weight',
            'a.attribute',
            'a.cost',
            'a.last_cost',
            'a.lower_selling_price',
            'a.remark',
            'a.is_product_materiel',
            DB::raw('SUM(in_storage_num) as total_amount')
            )
            ->from('materiel_type as a')
            ->leftJoin('storage_manage as b', 'a.id', '=', 'b.type_id')
            ->leftJoin('storage_shelf as d', 'd.id', '=', 'b.shelf_id')
            ->leftJoin('storage_shelf_location as e', 'e.id', '=', 'b.location_id');

            if(!empty($data['is_product'])){
                $query-> where('a.id', $data['goods_id']);
            }else{
                $query->where('a.id',  $data['batch_no']);
            }
            $query -> where('a.main_id',$data['main_id']);
            $info = $query -> where('a.delete_flag',0)
                   -> where('b.delete_flag',0)
                   -> first()->toArray();
            if(empty($info['id'])){
                $query = MaterielTypeModel::where([
                    'main_id'=>$data['main_id'],
                    'delete_flag'=>0
                ]);
                if(!empty($data['is_product'])){
                    $query -> where('id', $data['goods_id']);
                }else{
                    $query -> where('id',  $data['batch_no']);
                }
                $info = $query -> first();
                if(empty($info)){
                    return "";
                }
                $info['type_id']=$info['id'];
                unset($info['id']);
            }
                    $info['product_content'] = [];
                    if(!empty($info) && $info['is_product_materiel'] == 1){
                        $productList = MaterielProductContentModel::select(
                            'a.id',
                            'b.materiel_name',
                            'b.type_name',
                            'b.materiel_img',
                            'b.materiel_no',
                            'a.product_id',
                            'a.num',
                            'a.price',
                            'a.type_id',
                            'a.total_price'
                            )
                            ->from('materiel_product_content as a')
                            ->leftJoin('materiel_type as b','b.id','=','a.type_id')
                            ->where('a.product_id',$info['type_id'])->get()->toArray();
                         if(!empty($productList)){
                             $info['product_content'] = $productList;
                         }
                   }
                    if(empty($info['id'])){
                        $info['shelf_name']="";
                        $info['location_name']="";
                        $info['storage_name']="";
                        $info['storage_id']=0;
                        $info['shelf_id']=0;
                        $info['location_id']=0;
                        $info['id']=0;
                    }
                    return $info;
    }

    //商品批次信息
    static private function readBarCodeGoodsInfo($data)
    {
        //查询是否是组件id，如果是返回组件套餐id
        $query = MaterielTypeModel::select(
            'b.id',
            'a.id as type_id',
            'd.shelf_name',
            'e.location_name',
            'b.storage_name',
            'b.storage_id',
            'b.shelf_id',
            'b.location_id',
            'a.materiel_name',
            'a.materiel_img',
            'a.type_name',
            'a.materiel_no',
            'a.selling_price',
            'a.is_use_serial',
            'a.materiel_class_id',
            'a.materiel_unit',
            'a.is_album',
            'a.is_product_materiel',
            'a.length',
            'a.width',
            'a.height',
            'a.weight',
            'a.attribute',
            'a.cost',
            'a.last_cost',
            'a.lower_selling_price',
            'a.remark',
            'a.is_product_materiel',
            'a.bar_code',
            DB::raw('SUM(in_storage_num) as total_amount')
            )
            ->from('materiel_type as a')
            ->leftJoin('storage_manage as b', 'a.id', '=', 'b.type_id')
            ->leftJoin('storage_shelf as d', 'd.id', '=', 'b.shelf_id')
            ->leftJoin('storage_shelf_location as e', 'e.id', '=', 'b.location_id');


            if(!empty($data['is_product'])){
                $query -> where('a.id',$data['goods_id']);
            }else{
                $query -> where('a.bar_code',$data['batch_no']);
            }
                $query->where('a.main_id',$data['main_id']);
            $info = $query -> where('a.delete_flag',0)
            -> where('b.delete_flag',0)
            -> first()->toArray();

            if(empty($info['id'])){
                $query = MaterielTypeModel::where([
                    'main_id'=>$data['main_id'],
                    'delete_flag'=>0
                    ]);
                if(!empty($data['is_product'])){
                    $query -> where('id',$data['goods_id']);
                }else{
                    $query -> where('bar_code',$data['batch_no']);
                }
                $info = $query -> first();
                if(empty($info)){
                    return "";
                }
                $info['type_id']=$info['id'];
                unset($info['id']);
            }

            $info['product_content'] = [];
            if(!empty($info) && $info['is_product_materiel'] == 1){
                $productList = MaterielProductContentModel::select(
                    'a.id',
                    'b.materiel_name',
                    'b.type_name',
                    'b.materiel_img',
                    'b.materiel_no',
                    'a.product_id',
                    'a.num',
                    'a.price',
                    'a.type_id',
                    'a.total_price'
                    )
                    ->from('materiel_product_content as a')
                    ->leftJoin('materiel_type as b','b.id','=','a.type_id')
                    ->where('a.product_id',$info['type_id'])->get()->toArray();
                    if(!empty($productList)){
                        $info['product_content'] = $productList;
                    }
            }
            if(empty($info['id'])){
                $info['shelf_name']="";
                $info['location_name']="";
                $info['storage_name']="";
                $info['storage_id']=0;
                $info['shelf_id']=0;
                $info['location_id']=0;
                $info['id']=0;
            }
            return $info;
    }

    static public function checkList($condition,$data,$keyword){
       return CheckStorageManageModel::select(
           'a.id','check_no','b.nickname','sg_type','check_time'
           )
        ->from('check_storage_manage as a')
        ->leftJoin('admin as b','b.id','=','a.user_id')
        ->where($condition)
        ->where(function($query) use ($keyword) {
            $query->orWhere('b.nickname', 'like', '%'.$keyword.'%');
            $query->orWhere('a.check_no', 'like', '%'.$keyword.'%');
        })
        ->groupBy('check_no')
        ->orderBy('check_time','desc')
        ->paginate($data['pageSize'],['*'], '',$data['currentPage']);

    }

    static public function checkSkGoodsList($condition,$data,$keyword){

             $query=CheckStorageManageModel::select(
                'a.type_id',
                'a.yk_flag',
                'a.check_no',
                'c.materiel_name',
                 'is_cover',
                'c.materiel_img',
                'a.check_num','a.yk_num',
                'b.in_storage_num',
                'd.shelf_name','e.location_name',
                'b.storage_name','c.type_name',
                'c.materiel_no','a.storage_manage_id',
                'c.is_use_serial','c.is_product_materiel'
                )
                ->from('check_storage_manage as a')
                ->leftJoin('storage_manage as b','b.id','=','a.storage_manage_id')
                ->leftJoin('materiel_type as c','c.id','=','a.type_id')
                ->leftJoin('storage_shelf as d', 'd.id', '=', 'b.shelf_id')
                ->leftJoin('storage_shelf_location as e', 'e.id', '=', 'b.location_id')
                ->with('productContent',function($query){
                    $query->select(
                    'materiel_product_content.id',
                    'a.materiel_name',
                    'a.type_name',
                    'a.materiel_img',
                    'a.materiel_no',
                    'product_id',
                    'materiel_product_content.num',
                    'materiel_product_content.price',
                    'materiel_product_content.type_id',
                    'materiel_product_content.total_price'
                    )->leftJoin('materiel_type as a', 'a.id', '=', 'materiel_product_content.type_id')
                    ->where('materiel_product_content.delete_flag',0)
                    ->where('a.delete_flag',0);
                })
                ->where($condition)
                ->where('check_no',$data['check_no']);
                if(!empty($data['yk_flag'])){
                    $query->where('a.yk_flag',$data['yk_flag']);
                }
                if(!empty($keyword)){
                 $query->where(function($query) use ($keyword) {
                 $query->orWhere('c.materiel_name', 'like', '%'.$keyword.'%');
                 });
                }
                $data = $query->groupBy('storage_manage_id')
                ->groupBy('type_id')
                ->orderBy('check_time','desc')
                ->paginate($data['pageSize'],['*'], '',$data['currentPage'])->toArray();

                if(!empty($data['data'])){
                    foreach ($data['data'] as $k => $v){
                        if($v['is_product_materiel']) {
                            $data['data'][$k]['serial_list'] = [];
                            $SerialList = CheckSerialNumberModel::select("serial_number")->where([
                                "type_id" => $v['type_id'],
                                "storage_manage_id" => $v['storage_manage_id'],
                                "check_no" => $v['check_no'],
                            ])->where('status', 1)->first();

                            if (!empty($SerialList)) {
                                $data['data'][$k]['serial_list'] = explode(',', $SerialList['serial_number']);
                            } else {
                                $data['data'][$k]['serial_list'] = [];
                            }
                        }
                        else {
                            $SerialList = CheckSerialNumberModel::select("serial_number")->where([
                                "type_id" => $v['type_id'],
                                "storage_manage_id" => $v['storage_manage_id'],
                                "check_no" => $v['check_no'],
                            ])->where('status', 1)->first();

                            if (!empty($SerialList)) {
                                $data['data'][$k]['serial_list'] = explode(',', $SerialList['serial_number']);
                            } else {
                                $data['data'][$k]['serial_list'] = [];
                            }
                        }
//                            if(!empty($v['product_content'])){
//                                foreach ($v['product_content'] as $pk=>$pv){
//var_dump($pv['type_id']);die;
//                                $serialList = CheckSerialNumberModel::select("serial_number")->where([
//                                    "type_id"           => $pv['type_id'],
//                                    "product_id"        => $v['type_id'],
//                                    "storage_manage_id" => $v['storage_manage_id'],
//                                    "check_no"          => $v['check_no'],
//                                    "goods_flag"        => 2,
//                                    ])->where('status',1)->first();
//var_dump($serialList);die;
//                                    if(!empty($serialList)){
//                                        $data['data'][$k]['product_content'][$pk]['serial_list'] = explode(',', $serialList['serial_number']);
//                                    }else{
//                                        $data['data'][$k]['product_content'][$pk]['serial_list'] = [];
//                                    }
//                                }
//                            }
//                        }else{
//
//                            $SerialList = CheckSerialNumberModel::select("serial_number")->where([
//                                "type_id"           => $v['type_id'],
//                                "storage_manage_id" => $v['storage_manage_id'],
//                                "check_no"          => $v['check_no'],
//                                "goods_flag"        => 1,
//                            ])->where('status',1)->first();
//
//                            if(!empty($SerialList)){
//
//                                $data['data'][$k]['serial_list'] = explode(',', $SerialList['serial_number']);
//                            }else{
//                                $data['data'][$k]['serial_list'] = [];
//                            }
//                        }
                    }
                }

                return $data;
    }

}
